const app = getApp();
const Controller = require('../controllers/controllers').controller
const util = require('../../utils/util.js')


const SEQUENCE_MODE = 1 //列表循环
const RANDOM_MOD = 2 //随机循环
const SINGLE_CYCLE_MOD = 3 // 单曲循环
const manage = wx.getBackgroundAudioManager()


Page({
  data: {
    isloading:true,
    title: '正在播放',
    isIphoneX: false,
    audioId: '', //音频id
    collectBtnShow: true, //收藏按钮显示
    showCollectBox: true, //显示收藏弹出窗
    animationData: {}, //弹出窗效果
    isShowPicker: true, //弹出窗显示
    shadowContentId: 0, //弹出窗当前内容显示id 0 音频简介 1 播放列表 2 历史歌单列表
    isShowSelect: true, //多选radio
    isShowSingleSelect: false, //显示radio按钮
    currentId: 0, //当前radio的id
    swiperCurrentId: 0, //swiper当前的索引
    currentPlayListTitle: '历史听单',
    mode: 1,
    play: 2, //1是暂停，2是播放
    current: 1,
    swiperstart: 0,
    swiperend: 0,
    swipermove: 0,
    menuList: [{
        'index': 2,
        'menu': '我的收藏'
      },
      {
        'index': 1,
        'menu': '推荐听单'
      },
      {
        'index': 0,
        'menu': '历史听单'
      }
    ], //菜单集合
    menuListcurrent: 1,
    menuListindex: 1,
    menuListactive: 1,
    animationData1: {},
    startPoint: {}, //触摸开始
    dotPoint: {}, //圆点坐标
    startAngle: 0, //开始角度
    tempAngle: 0, //移动角度
    downTime: 0, //按下时间
    upTime: 0, //抬起时间
    deg: 30,
    historyList: [], //历史听单
    historyPageNumber: 1,
    historyLastPage: null,
    recommendedList: [], //推荐听单
    recommendedPageNumber: 1,
    recommendedLastPage: null,
    collectionList: [], //收藏听单
    collectionPageNumber: 1,
    collectionLastPage: null,
    isSelected: 0, //已选中的数量
    multipleList: [], //存储选中的id
    isMultipled: false, //是否已全选
    options: {}, //页面的参数
    audioList: [], //播放列表
    audioListPageNumber: 1,
    audioListLastPage: null,
    audioListTotalRow: 0,
    audioDetail: '', //音频信息
    isCheckCollect: 0, //检测是否点赞收藏
    thePosition: 0, //用来保存暂停时播放位置
    cur: '--:--', //当前时间
    currentTime: 0,
    playurl: '',
    currentLyric: null,
    currentLineNum: -1,
    toLineNum: -1,
    currentSong: null,
    playMod: SEQUENCE_MODE,
    closetimecurrent: 0,
    settimebool: false,
    percent: 0,
    lyriccurrent: 0,
    lyricmultiple: 1,
    lyricchange: false,
    setInter: null,
    lyricTop: -1,
    lyric: [],
    LyricHeight:160,
    LyricItemHeight: 30,
    wordstime: 0,
    fistplay: true,
    options: '',
    lyricstarttime: '',
    lyricstarttime1:'',
    // 转盘转动
    timer: null,
    backrotate: 0,
    temporaryBackrotate: 0,
    screenWidth: 375,
    sildercurrent:0,
    lyricnums:3,
  },
  onLoad(options) {
    console.log(options+'=====================================')
    // 转盘转动
    const res = wx.getSystemInfoSync()
    this.setData({
      screenWidth: res.screenWidth
    })
    var that = this;
    if (options) {
      that.setData({
        options: options
      })
    }
    //达人
    if (options.albumnavcurrent) {
      that.setData({
        menuListcurrent: options.albumnavcurrent == 0 ? 0 : 2,
        menuListindex: options.albumnavcurrent == 0 ? 0 : 2,
      })
    }
    if (options && options.audioId) {
      that.setData({
        audioId: options.audioId
      })
      that.audioDetail(options.audioId)
    }
    if (app.globalData.closetimecurrent > 0) {
      this.setData({
        closetimecurrent: app.globalData.closetimecurrent,
        settimebool: true
      })
    }
    if(options.scene){
      const id = decodeURIComponent(options.scene);
      console.log(id)
      this.setData({
        audioId: id
      })
      this.audioDetail(id)
    }

  },
  onShow() {
    var that = this;
    that.setData({
      isIphoneX: app.globalData.isIphoneX,
      playMod: app.globalData.playMod,
      play: app.globalData.play
    })
    
    if ((wx.getStorageSync('userInfos').id != that.data.options.userId) && that.data.options.userId) {
      that.data.menuList[0].menu = "TA的收藏";
      that.setData({
        menuList: that.data.menuList
      })
    }else{
      that.data.menuList[0].menu = "我的收藏";
      that.setData({
        menuList: that.data.menuList
      })
    }
    // if (that.data.menuListcurrent == 0) {
      
    // }
    if (that.data.audioId) {
      that.checkCollect(that.data.audioId)
    }
    that.getHistoryData();
    that.getRecommendedData();
    that.getCollectListData();
    
  },
  onReady(e) {
    this.Dialog = this.selectComponent('#Dialog');
    // this.playcontrol = this.selectComponent('#playcontrol');
  },
  // onHide(){
  //   wx.showToast({
  //     title:'1'
  //   })
  //   manage.pause()
  // },
  // 分享按钮
  shareBtn(e) {
    if(this.data.currentSong){
      app.share(e.currentTarget.dataset.id,3,this.data.currentSong.title || '',this.data.currentSong.imgUrl || '')
    }else{
      app.share(e.currentTarget.dataset.id,3,'','')
    }
    
    // wx.navigateTo({
    //   url: '/pages/AudioSharing/AudioSharing?type=3&id=' + e.currentTarget.dataset.id + '&title=' + this.data.currentSong.title,
    // })
  },
  menuListswiper(e) {

    console.log("menuListswiper")
    var index = e.detail.current || 0
    var menuListindex = index
    if (index >= 6) {
      index = 0
    }
    this.setData({
      menuListactive: index,
      menuListindex: menuListindex,
      currentPlayListTitle: this.data.menuList[index].menu || '历史听单',
    })

    let historyList = this.data.historyList
    let collectionList = this.data.collectionList
    historyList.map(item => {
      item.select = false
    })
    collectionList.map(item => {
      item.select = false
    })
    this.setData({
      isShowSelect: true,
      multipleList: [],
      isSelected: 0,
      isMultipled: false,
      historyList,
      collectionList
    })
    if (this.data.fistplay) {
      this.playLists(this.data.options)
    } else {
      this.playLists()
    }

  },
  // 转盘转动(ing)
  bindtransition(e) {
    let dx = e.detail.dx;
    if (this.data.timer) {
      return;
    }
    console.log('dx',dx)
    this.data.timer = setTimeout(() => {
      if (!this.data.timer) {
        return;
      }
      this.setData({
        temporaryBackrotate: Math.floor(-dx / this.data.screenWidth * 3 * 100) / 100
      })
      this.data.timer = null;
    }, 1000 / 60);
  },
  // 转盘转动(ed)
  bindanimationfinish(e) {
    if (this.data.timer) {
      clearTimeout(this.data.timer)
      this.data.timer = null;
    }
    let backrotate = this.data.backrotate;
    this.setData({
      backrotate: backrotate + Math.round(this.data.temporaryBackrotate),
      temporaryBackrotate: 0,
    })
  },
  //第一次获取数据
  playLists(options) {
    let that = this;
    if (app.globalData.songlist && app.globalData.songlist.length > 0) {
      that.setData({
        songlist: app.globalData.songlist,
        fistplay: false
      })
      // if (!that.data.currentSong) {
        that.setData({
          currentSong: that.data.songlist[app.globalData.currentIndex]
        })
      // }
      app.globalData.songlist=that.data.songlist
      that._init()
    } else {
      
      if (this.data.menuListindex == 2) {
        // 获取历史--听单数据
        that.setData({
          songlist: that.data.historyList,
        })

      }
      if (this.data.menuListindex == 1) {
        // 获取推荐--听单数据
        // this.getRecommendedData(options);
        that.setData({
          songlist: that.data.recommendedList,
        })
      }
      if (this.data.menuListindex == 0) {
        // 获取收藏--听单数据
        // this.getCollectListData(options);
        // this.getRecommendedData(options);
        that.setData({
          songlist: that.data.collectionList,
        })
      }
      app.globalData.songlist=that.data.songlist
      that._init()
    }
    

  },
  // 获取历史--听单数据
  getHistoryData() {
    let that = this
    let params = {
      page: 1,
      pageSize: 100,
    }
    if (that.data.options.userId) {
      params.userId = that.data.options.userId
    }
    Controller.historyList(params)
      .then(res => {
        if (res.data && res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
          that.setData({
            historyList: res.data.baseData.list
          })
          that.playLists();
        }else{
          that.setData({
            menuListcurrent:1
          })
        
        }
        
      }).catch(res=>{
        that.setData({
          menuListcurrent:1
        })
      
      })
  },
  // 获取推荐--听单数据
  getRecommendedData() {
    
      let that = this
      Controller.audioList({
          isRecommend: 1,
          page: 1,
          pageSize: 100,
        })
        .then(res => {
          if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
            that.setData({
              recommendedList: res.data.baseData.list
            })
            // if(this.data.historyList.length<=0){
              that.playLists();
            // }
          }
        })

  },
  // 获取收藏--听单数据
  getCollectListData() {

    if (!wx.getStorageSync('logintoken')) {
      app.ToLogin()
    } else {
      let that = this
      let params = {
        page: 1,
        pageSize: 100
      }
      if (that.data.options.userId) {
        params.userId = that.data.options.userId
      }
      Controller.collectList(params)
        .then(res => {
          if (res.data.baseData && res.data.baseData.list && res.data.baseData.list.length > 0) {
            that.setData({
              collectionList: res.data.baseData.list
            })
          }
        })
    }
  },


  // 音频详情
  audioDetail(audioId) {
    Controller.audioDetail({
        audioId
      })
      .then(res => {
        app.globalData.currentIndex = 0
        app.globalData.songlist = [res.data.baseData]
        this.playLists()
      })
  },

  // 播放列表按钮
  listBtn() {
    console.log('列表按钮')
    let _this = this;
    //创建动画
    var animation = wx.createAnimation({
      duration: 500, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    // 在当前页面添加animation属性 
    _this.animation = animation
    setTimeout(function () {
      _this.fadeIn(); //调用显示动画
    }, 20)
    _this.setData({
      isShowPicker: false,
      shadowContentId: 1
    })
  },
  RowBtn(e) {

    let row = e.currentTarget.dataset.row
    let swiperCurrentId = this.data.swiperCurrentId
    console.log('箭头', e, row, swiperCurrentId)
    if (row == 'left') {
      if (swiperCurrentId > 0) {
        console.log('left')
        swiperCurrentId--
      }
    } else {
      if (swiperCurrentId < 2) {
        console.log('right')
        swiperCurrentId++
      }
    }

    this.setData({
      swiperCurrentId,
      menuListcurrent:swiperCurrentId,
      currentPlayListTitle: this.data.menuList[swiperCurrentId].menu
    })
    // if (this.data.swiperCurrentId == 0) {
    //   // 获取历史--听单数据
    //   console.log('获取历史--听单数据')
    //   this.getHistoryData();
    // }
    // if (this.data.swiperCurrentId == 1) {
    //   // 获取推荐--听单数据
    //   console.log('获取推荐--听单数据')
    //   this.getRecommendedData();
    // }
    // if (this.data.swiperCurrentId == 2) {
    //   // 获取收藏--听单数据
    //   console.log('获取收藏--听单数据')
    //   this.getCollectListData();
    // }
  },
  // 简介更多按钮
  moreBtn() {
    console.log('更多按钮')
    let _this = this;
    _this.setData({
      isShowPicker: false,
      shadowContentId: 0
    })
    //创建动画
    var animation = wx.createAnimation({
      duration: 500, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    // 在当前页面添加animation属性 
    _this.animation = animation
    setTimeout(function () {
      _this.fadeIn(); //调用显示动画
    }, 20)

  },
  // 播放器旋转按钮
  rotaryBtn(e) {
    console.log('列表按钮', e)
    // let list = [1,0,2]
    let index = e.currentTarget.dataset.index;
    let _this = this;
    //创建动画
    var animation = wx.createAnimation({
      duration: 500, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    // 在当前页面添加animation属性 
    _this.animation = animation
    setTimeout(function () {
      _this.fadeIn(); //调用显示动画
    }, 20)
    _this.setData({
      menuListcurrent: index,
      isShowPicker: false,
      shadowContentId: 2,
      currentPlayListTitle: _this.data.menuList[index].menu
    })
  },
  // 隐藏弹出窗
  cancleBtn() {
    let _this = this;
    var animation = wx.createAnimation({
      duration: 600, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'linear', //动画的效果 默认值是linear
    })
    _this.animation = animation
    _this.fadeDown()
    //先执行下滑动画，再隐藏模块
    setTimeout(function () {
      _this.setData({
        isShowPicker: true,
        isShowSelect: true
      })
      // _this.rowBtnFn()
    }, 500)
  },
  //动画集
  fadeIn() {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown() {
    this.animation.translateY(800).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  // 收藏按钮
  async collectBtn(e) {
    if (!wx.getStorageSync('logintoken')) {
      app.ToLogin()
      return
    }
    let showCollectBox = this.data.showCollectBox;
    let that = this;
    let rid = e.currentTarget.dataset.rid
    console.log('收藏按钮', e)
    /* 
      判断点击收藏按钮的时候是否已经选中
      选中的话 取消收藏 反之亦然
    */
    showCollectBox = !this.data.collectBtnShow ? true : false
    that.setData({
      collectBtnShow: !this.data.collectBtnShow,
      showCollectBox
    })
    // 防止多次点击收藏按钮
    if (that.timer) {
      clearTimeout(this.timer)
    }
    that.timer = setTimeout(() => {

      if (!that.data.isCheckCollect) { //收藏
        that.collectfn(rid);
      } else {
        //取消收藏
        that.delCollectfn(that.data.isCheckCollect, rid);
      }
      // 检测是否点赞收藏
      that.setData({
        showCollectBox: true
      })
    }, 1000)
  },
  commentBtn(e){
    if (!wx.getStorageSync('logintoken')) {
      app.ToLogin()
      return
    }
    wx.navigateTo({
      url:'/pages/Comment/Comment?rid='+this.data.currentSong.id+'&type=3'
    })
  },
  // 检测是否点赞收藏
  checkCollect(rid) {
    Controller.checkCollect({
        type: 3,
        rid,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        console.log(res)
        if (res.code == 0) {
          this.setData({
            isCheckCollect: res.data.baseData,
            collectBtnShow: res.data.baseData ? false : true
          })
        }
      })
  },
  // 点赞收藏方法
  collectfn(rid) {
    let that = this
    Controller.collect({
        rid,
        type: 3,
        bodyId: rid,
        bodyType: 3
      })
      .then(res => {
        app.updateScore(9)
        if (res.code == 0) {
          that.checkCollect(rid)
        }
      }).catch(err => {
        console.log('err', err)
      })
  },
  // 取消收藏
  delCollectfn(ids, rid) {
    let that = this
    Controller.delCollect({
        ids
      })
      .then(res => {
        console.log('取消收藏', res)
        if (res.code == 0) {
          that.checkCollect(rid)
        }
      }).catch(err => {
        console.log('err', err)
      })
  },

  // 多选按钮
  selectHandle() {
    this.setData({
      isShowSelect: !this.data.isShowSelect
    })
  },
  // 单个选择按钮
  async singleSelectBtn(e) {
    console.log('单个选择按钮', e)
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    let rid = e.currentTarget.dataset.rid;
    let menuListindex = this.data.menuListindex;
    let list = []
    if (menuListindex == 0) { //历史列表
      list = this.data.historyList
    } else if (menuListindex == 2) { //收藏列表
      list = this.data.collectionList
    }
    let result = await this.singleChoiceOperation(list, id, type, rid);
    if (menuListindex == 0) { //历史列表
      this.setData({
        historyList: result
      })

    } else if (menuListindex == 2) { //收藏列表
      this.setData({
        collectionList: result
      })

    }

  },
  // 播放列表单选按钮
  async singleAudioBtn(e) {
    console.log('播放列表单选按钮', e)
    let id = parseInt(e.currentTarget.dataset.id);
    let audioList = this.data.audioList;
    let result = await this.singleChoiceOperation(audioList, id);
    this.setData({
      audioList: result
    })
  },
  // 单选处理操作
  singleChoiceOperation(list, id, type, rid) {
    let isMultipled = this.data.isMultipled; //是否全选
    let isSelected = this.data.isSelected; //已选多少个
    let multipleList = this.data.multipleList; //存储选中的id
    // 将数据以字符串的方式存进数组里面‘1-2-3’或者'5'
    // 判断是否已经选中
    let strData = ''
    console.log(typeof (type) == 'undefined', typeof (rid))
    // 判断是历史听单还是收藏听单
    if (typeof (type) != 'undefined' && typeof (rid) != 'undefined') {
      // rid-type-audioId
      strData = rid + '-' + type + '-' + id
    } else {
      strData = '' + id
    }

    if (multipleList.includes(strData)) {
      // 选中的，就直接删除掉
      let idx = multipleList.indexOf(strData);
      multipleList.splice(idx, 1)
      isSelected--
      isMultipled = false
    } else {
      multipleList.push(strData)
      // 判断是否全选
      if (multipleList.length == list.length) {
        isMultipled = true
      }
      isSelected++
    }

    console.log('单个选择按钮', strData, isSelected)
    for (let item of list) {
      let strCur = ''
      if (typeof item.type != 'undefined') {
        // 收藏的对应字段
        strCur = item.rid + '-' + item.type + '-' + item.id
      } else {
        // 历史听单的historyId
        strCur = '' + item.historyId
      }

      if (multipleList.includes(strCur)) {
        item.select = true
      } else {
        item.select = false
      }
    }
    this.setData({
      isShowSingleSelect: true,
      currentId: id,
      multipleList,
      isSelected,
      isMultipled
    })
    return list
  },
  // 历史，收藏全选按钮
  async multipleSelectBtn() {
    let menuListindex = this.data.menuListindex;
    let list = []
    if (menuListindex == 0) { //历史列表
      list = this.data.historyList

    } else if (menuListindex == 2) { //收藏列表
      list = this.data.collectionList

    }
    let result = await this.selectAllOperation(list)
    if (menuListindex == 0) { //历史列表
      this.setData({
        historyList: result
      })

    } else if (menuListindex == 2) { //收藏列表
      this.setData({
        collectionList: result
      })

    }
  },
  // 播放列表的全选操作
  async multipleAudioBtn() {
    let audioList = this.data.audioList;
    let result = await this.selectAllOperation(audioList)
    this.setData({
      audioList: result
    })
  },
  // 全选处理操作
  selectAllOperation(list) {
    let multipleList = this.data.multipleList; //存储选中的id
    let isMultipled = this.data.isMultipled; //是否全选
    let isSelected = this.data.isSelected; //已选多少个
    console.log('全选按钮')
    if (multipleList.length != 0) {
      // 判断是否全部选中
      if (multipleList.length == list.length) {
        multipleList.length = 0
        isMultipled = false
        isSelected = 0
        list.map(item => {
          item.select = false
        })
      } else {
        list.map(item => {
          let strCur = ''
          if (typeof item.type != 'undefined' && typeof item.rid != 'undefined') {
            strCur = item.rid + '-' + item.type + '-' + item.id
          } else {
            strCur = '' + item.historyId
          }
          if (!item.select) {
            item.select = true
            multipleList.push(strCur)
          }
        })
        isMultipled = true
        isSelected = list.length
      }
    } else {
      list.map(item => {
        item.select = true
        let strCur = ''
        if (typeof item.type != 'undefined' && typeof item.rid != 'undefined') {
          // 收藏听单
          strCur = item.rid + '-' + item.type + '-' + item.id
        } else {
          // 历史听单
          strCur = '' + item.historyId
        }
        multipleList.push(String(strCur))
      })
      isMultipled = true
      isSelected = list.length
    }
    this.setData({
      multipleList,
      isMultipled,
      isSelected
    })
    return list;
  },
  // 删除按钮
  multipledUnsubscribeBtn() {
    let menuListindex = this.data.menuListindex
    if (menuListindex == 0) { //删除历史听单
      this.delHistortList()
    } else if (menuListindex == 2) { //删除收藏听单
      this.delPlayCollect()
    }
  },
  // 删除历史听单
  delHistortList() {
    let multipleList = this.data.multipleList
    let str = multipleList.join(',')
    let that = this
    if (multipleList.length != 0) {
      // 弹出窗
      that.Dialog.ShowDialog({
        title: '是否删除已选的音频',
        type: 'Confirm',
        callback(obj) {
          if (obj.name == 'confirm') {
            Controller.removeHistory({
                ids: str
              })
              .then(res => {
                if (res.code == 0) {
                  that.setData({
                    isShowSelect: true,
                    isSelected: 0,
                    historyPageNumber: 1,
                    historyList: [],
                    multipleList: [],
                    isMultipled: false
                  })
                  wx.showToast({
                    title: '删除音频成功',
                    duration: 1000
                  })
                  // 获取历史--听单数据
                  if (that.data.options && that.data.options.userId) {
                    that.getHistoryData();

                  } else {
                    that.getHistoryData();

                  }
                }
              })
          }
          that.Dialog.CloseDialog();
          that.setData({
            isShowSelect: true
          })
        }
      })
    } else {
      wx.showToast({
        title: '请选择音频',
        icon: 'none',
        duration: 1000
      })
    }
  },
  // 删除收藏听单
  delPlayCollect() {
    let multipleList = this.data.multipleList
    let str = multipleList.join(',')
    let that = this

    if (multipleList.length != 0) {
      // 弹出窗
      that.Dialog.ShowDialog({
        title: '是否收藏的音频',
        type: 'Confirm',
        callback(obj) {
          console.log('eee', obj)
          if (obj.name == 'confirm') {
            // 参数:rid-type-audioId按逗号分隔，如1-2-3,2-3-4
            Controller.delPlayCollect({
                ids: str
              })
              .then(res => {
                console.log(res)
                if (res.code == 0) {
                  that.setData({
                    isShowSelect: true,
                    isSelected: 0,
                    collectionPageNumber: 1,
                    collectionList: [],
                    multipleList: [],
                    isMultipled: false
                  })
                  wx.showToast({
                    title: '删除音频成功',
                    duration: 1000
                  })
                  if (that.data.options && that.data.options.userId) {
                    that.getCollectListData(that.data.options.userId);

                  } else {
                    that.getCollectListData();

                  }
                }
              })
          }
          that.Dialog.CloseDialog();
          that.setData({
            isShowSelect: true
          })
        }
      })
    } else {
      wx.showToast({
        title: '请选择音频',
        icon: 'none',
        duration: 1000
      })
    }
  },
  // 点击某首歌，播放该歌曲
  listenMusic(e) {
    console.log('点击某首歌，播放该歌曲', e)
    let audioId = e.currentTarget.dataset.audioid //当前歌曲的id
    // 音频详情
    this.audioDetail(audioId);
  },
  // 下载音频
  downAudioBtn(e) {
    let audioId = e.currentTarget.dataset.id //当前歌曲的id
    Controller.download({
        rid: audioId,
        token: wx.getStorageSync('logintoken')
      })
      .then(res => {
        if (res.code == 0) {
          wx.showToast({
            title: '下载成功'
          })
        }
      })
  },

  onHide() {
    clearTimeout(this.timer)
  },
  async onShareAppMessage(e) {
    let title = e.target.dataset.title
    let swiperId = e.target.dataset.swiperid
    let userId = wx.getStorageSync('userInfos').id
    if (e.from == "button") {
      let posterImageUrl = await this.getPosterImage()
      console.log('posterImageUrl', posterImageUrl)
      let obj = {
        title,
        imageUrl: posterImageUrl,
        success(res) {
          console.log('点击页面内的分享按钮--onShareAppMessage分享成功', res)
        },
        fail(err) {
          console.log('点击页面内的分享按钮--onShareAppMessage-fail', err)
        }
      }

      if (swiperId == 1) {
        let recommendedList = encodeURIComponent(JSON.stringify(this.data.recommendedList))
        obj.path = '/pages/Playing/Playing?swiperId=' + swiperId + '&recommendedList=' + recommendedList
      } else if (swiperId == 0 || swiperId == 2) {
        obj.path = '/pages/Playing/Playing?swiperId=' + swiperId + '&userId=' + userId
      }

      // 当前音频上的分享按钮
      if (e.target && e.target.dataset && e.target.dataset.id) {
        obj.path = '/pages/Playing/Playing?audioId=' + e.target.dataset.id
        console.log(obj)
      }
      return obj
    }
  },
  // 获取海报图片
  getPosterImage() {
    // 1合辑 2栏目 3音频 4达人榜 5推荐听单，6历史听单，7我的收藏，8达人主页，9晒一晒，10小程序名片
    let type = '';
    let currentPlayListTitle = this.data.currentPlayListTitle
    if (currentPlayListTitle == '历史听单') { //6历史听单
      type = 6
    } else if (currentPlayListTitle == '推荐听单') { //5推荐听单
      type = 5
    } else if (currentPlayListTitle == '我的收藏' || currentPlayListTitle == 'TA的收藏') { //7我的收藏
      type = 7
    }
    return new Promise(resolve => {
      Controller.shareImg({
          type,
          token: wx.getStorageSync('logintoken')
        })
        .then(res => {
          console.log(res)
          if (res.code == 0) {
            resolve(res.data.baseData)
          }
        })
    })
  },

  //初始化
  _init(flag= false) {
    if(app.globalData.songlist && app.globalData.songlist.length>0){
      let currentIndex = app.globalData.currentIndex || 0;
      let songlist = (app.globalData.songlist.length && app.globalData.songlist)
      let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songlist && songlist[app.globalData.currentIndex])
      let duration = currentSong && currentSong.duration
      this.setData({
        currentSong: currentSong,
        duration: duration,
        songlist: songlist,
        currentIndex: currentIndex
      })
      this._getPlayUrl(currentSong,flag)
      // if(flag){
      //   this._getPlayUrl(currentSong,flag)
      // }
      this._getLyric(currentSong)
      
    }

  },
  // 获取播放地址
  _getPlayUrl(currentSong,flag) {
    const _this = this
    if (currentSong && currentSong.audioUrl) {
      
      _this._createAudio(currentSong,flag)
      
    } else {
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
    
  },
  // 创建播放器
  _createAudio(currentSong,flag) {
      
    if(manage.src != currentSong.audioUrl) {
      manage.seek(0);
      this.setData({
        play:1,
        toLineNum:-1,
        currentLineNum:-1,
        lyricTop:0,
        currentTime:0
      })
      app.globalData.play=1
      if(flag){
        manage.src = currentSong.audioUrl
        manage.title = currentSong.title 
        manage.coverImgUrl=currentSong.imgUrl
        app.updateScore(5,currentSong.id)
      }else{
        manage.src = '1'
        manage.title = currentSong.title 
        manage.coverImgUrl=currentSong.imgUrl
        manage.stop()
      }
      
    }else{
      this.percenttime()
      manage.onPause(()=>{
        manage.pause()
      })
    }

    this.setData({isloading:false})
    this.listenmusic()

    
  },
  listenmusic(){
    manage.onPlay(()=>{
      this.setData({
        play: 2,
      })
      app.globalData.play = 2
      app.globalData.currentSong = this.data.currentSong
      app.play(this.data.currentSong.id)
    })

    manage.onPause(()=>{
      this.setData({
        play: 1,
      })
      app.globalData.play = 1
      app.globalData.currentSong = this.data.currentSong
      // 更新收听时长接口
      Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
    })
    // 监听音乐暂停。
   
    manage.onEnded(()=>{
      this.setData({
        play: 1,
      })
      app.globalData.play = 1
      app.globalData.currentSong = this.data.currentSong
      Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init(true)
        return
      }

      this.endnext()
    })
    // 监听音乐停止。
   
    this.onTimeUpdate()
  },
  onTimeUpdate(time) {
    // 监听播放拿取播放进度
    manage.onTimeUpdate(() => {
      this.percenttime()
    })
  },
  percenttime(){
    const currentTime = manage.currentTime;
    const duration = manage.duration
    console.log(manage.duration)
    this.setData({
      currentTime: this._formatTime(currentTime),
      duration: this._formatTime(duration),
      percent: currentTime / duration * 100,
      sildercurrent:(this.data.percent*540)/100
    })

    if (this.data.lyric.length > 0) {
      if (currentTime <= 0) {
        this.handleLyric(0)
        this.setData({
          lineNum: -1
        })
      } else {
        this.handleLyric(currentTime)
      }

    }
  },
  // 滑动
  musicchange(e) {
    var current = Number(e.detail.value);
    var duration = this._formatSecod(this.data.duration) || 0;
    var max = 540
    var change = '';
    change = current / max * duration;

    manage.seek((change || 0))
    this.onTimeUpdate(change)
  },
  _formatSecod(time) {
    time = time || 0
    if (typeof time == 'string') {
      var min = time.split(':')[0];
      var sec = time.split(':')[1];
      var s = Number(min * 60) + Number(sec);
    }
    return s
  },

  _formatTime(interval) {
    interval = interval | 0
    const minute = interval / 60 | 0
    const second = this._pad(interval % 60)
    return `${minute}:${second}`
  },
  /*秒前边加0*/
  _pad(num, n = 2) {
    let len = num.toString().length
    while (len < n) {
      num = '0' + num
      len++
    }
    return num
  },
  changeMod() {
    let playMod = this.data.playMod + 1
    if (playMod > SINGLE_CYCLE_MOD) {
      playMod = SEQUENCE_MODE
    }
    this.setData({
      playMod: playMod
    })
    app.globalData.playMod = playMod
  },
  prev() {
    if (manage.src) {
      if (app.globalData.currentIndex != this.getNextIndex(false)) {
        app.globalData.currentIndex = this.getNextIndex(false)
        this._init(true)
      }
    } else {
      app.globalData.songlist = this.data.songlist
      this._init(true);
    }
  },
  next() {
    if (manage.src) {
      if (app.globalData.currentIndex != this.getNextIndex(true)) {
        app.globalData.currentIndex = this.getNextIndex(true)
        this._init(true)
      }
    } else {
      app.globalData.songlist = this.data.songlist
      this._init(true);
    }

  },
  endnext() {
    if (app.globalData.currentIndex != this.getNextIndex(true)) {
      app.globalData.currentIndex = this.getNextIndex(true)
      this._init(true)
    }
  },
  // 下一首歌曲的id
  getNextIndex(nextFlag) {
    let ret,
      currentIndex = Number(app.globalData.currentIndex),
      mod = this.data.playMod,
      len = this.data.songlist.length || 1
    // 随机
    if (mod === RANDOM_MOD) {
      ret = util.randomNum(len)
    } else {
      // 下一首
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  // 音乐播放开关
  togglePlaying() {
    console.log(manage.src)
    var that = this;
    var play = 2
    if (manage.src && manage.src!='1') {
      // 获取后台音乐播放状态
      wx.getBackgroundAudioPlayerState({
        success(res) {
          var status = res.status
          
          if (status == 1) {
            // wx.pauseBackgroundAudio()
            manage.pause()
            play = 1
          } else {
            // wx.playBackgroundAudio()
            manage.play()
            play = 2
          }
          that.setData({
            play: play
          })
          app.globalData.play=play
        },fail(res){

        }
      })
    } else {
      app.globalData.songlist = this.data.songlist
      that._init(true)
    }
    that.selectComponent('#Footer').playmusic();
  },

  playthis(e) {
    const index = e.currentTarget.dataset.index
    const current = e.currentTarget.dataset.current
    app.globalData.currentIndex = index
    if (current && current == 0) {
      app.globalData.songlist = this.data.historyList
    } else if (current && current == 1) {
      app.globalData.songlist = this.data.recommendedList
    } else if (current && current == 2) {
      app.globalData.songlist = this.data.collectionList
    } else {
      app.globalData.songlist = this.data.songlist
    }

    this._init(true)
  },
  bindPickerChange: function (e) {
    var that = this;
    that.Dialog.ShowDialog({
      type: 'Pager',
      callback: res => {
        this.Dialog.CloseDialog();
      }
    })
  },
  toastTime(res) {
    var time = res.detail.time;
    var close = res.detail.close;
    if (time > 0 && !close) {
      this.setData({
        closetimecurrent: time,
        settimebool: true,
      })
    } else {
      if (close) {
        this.setData({
          closetimecurrent: 0,
          settimebool: false
        })
      } else {
        this.setData({
          closetimecurrent: 0,
          settimebool: false,
          play: 1
        })
        manage.pause()
      }
    }
  },
  // 获取歌词
  _getLyric(currentSong) {
    var that = this;
    if (currentSong.words) {
      var lyric = ''
      if (typeof currentSong.words == 'string' && currentSong.words) {
        lyric = JSON.parse(currentSong.words);
      } else {
        lyric = currentSong.words;
      }

      for (let item of lyric) {
        item.time = that._formatSecod(item.time) || ''
      }
      that.setData({
        lyric: lyric
      })

      var query = wx.createSelectorQuery();
      query.select('#line0').boundingClientRect();
      query.exec(function (res) {
        if (res && res.length>0 && res[0] && res[0].height) {
          that.setData({
            LyricItemHeight: res[0].height
          })
        }
      })

      var query2 = wx.createSelectorQuery();
      query2.select('#lyricWrap').boundingClientRect();
      query2.exec(function (res) {
        if (res && res.length>0 && res[0] && res[0].height) {
          that.setData({
            LyricHeight: res[0].height
          })
        }
      })
      
      that.setData({
        lyricnums: Math.floor((that.data.LyricHeight / that.data.LyricItemHeight)/2)
      })
      console.log(this.data.lyricnums+'======+++++'+that.data.LyricHeight +'/'+ that.data.LyricItemHeight)
    } else {
      that.setData({
        lyric: []
      })
    }


    // this.listenmusic()
  },

  isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    }
  },
  // 歌词滚动回调函数
  handleLyric(currentTime) {
    
    if (this.data.lyricchange) {
      return
    }
    let lines = [{
        time: 0,
        txt: ''
      }],
      lyric = this.data.lyric,
      lineNum
    lines = lines.concat(lyric)

    for (let i = 1; i <= lines.length; i++) {
      if (i < lines.length - 1) {
        let time1 = lines[i].time,
          time2 = lines[i + 1].time
        if (currentTime > time1 && currentTime < time2) {
          lineNum = i - 1
          break;
        }
      } else {
        lineNum = 0 

      }
    }
    this.setData({
      currentLineNum: lineNum
    })

    let toLineNum = lineNum - this.data.lyricnums;
    console.log(this.data.lyricnums+'================')
    if (this.data.currentLineNum >= 0 && toLineNum != this.data.toLineNum) {
    
      this.setData({
        toLineNum: toLineNum 
      })
    } 
  },
  lyricscroll(e) {
    if (this.data.lyricchange) {
      var index = Math.round(e.detail.scrollTop / this.data.LyricItemHeight);
      var time = this.data.lyric[index+this.data.lyricnums].time || 0
      if (time != this.data.wordstime) {
        this.setData({
          wordstime: time
        })
        manage.seek((time || 0));
      }
    }
  },
  lyricstart(e) {
    var that = this;
    clearTimeout(that.data.lyricstarttime)
    clearTimeout(that.data.lyricstarttime1)
    that.data.lyricstarttime = setTimeout(res => {
      manage.pause()
      that.setData({
        lyricchange: true
      })
    }, 200)
    
  },
  
  lyricend(e) {
    var that = this
    clearTimeout(that.data.lyricstarttime)
    clearTimeout(that.data.lyricstarttime1)
    that.data.lyricstarttime1 =setTimeout(res => {
      if(that.data.lyricchange){
        if(manage.src && manage.src!='1'){
          manage.play()
          manage.seek((that.data.wordstime || 0));
        }else{
          that._init(true)
        }

        that.setData({
          lyricchange: false,
        })
      }
    },300)
  },
  PopSlowSongs(e) {
    var categoryId = e.currentTarget.dataset.categoryid;
    var tag = e.currentTarget.dataset.tag;
    wx.navigateTo({
      url: "/pages/PopSlowSongs/PopSlowSongs?id=" + categoryId + "&title=" + tag
    })
  },
  onShareAppMessage: function (e) {

    // // if (e.from == "button") {
      let obj = {
        title: '有氧FM·正在播放',
        path: "/pages/Playing/Playing?audioId="+ this.data.currentSong.id,
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      console.log(obj)
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // // if (e.from == "button") {
      let obj = {
        title: '有氧FM·正在播放',
        path: "/pages/Playing/Playing?audioId="+ this.data.currentSong.id,
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      console.log(obj)
      return obj
    // }
  },
})